/* MethodFault.cs -- 
   Copyright (C) 2008  Casey Marshall.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.  */


using System;
using SexpSharp;

namespace SexpSharp.RPC
{
	public sealed class MethodFault
	{
		private string name;
		private uint code;
		private string msg;

		public MethodFault(string name) : this(name, 0, "")
		{
		}

		public MethodFault(string name, uint code) : this(name, code, "")
		{
		}

		public MethodFault(string name, string msg) : this(name, 0, msg)
		{
		}

		public MethodFault(string name, uint code, string msg)
		{
			if (name.Length == 0)
				throw new ArgumentException("must be a nonempty string", "name");
			if (msg == null)
				throw new ArgumentNullException("msg");
			this.name = name;
			this.code = code;
			this.msg = msg;
		}

		public MethodFault(Expression expr)
		{
			List list = expr as List;
			if (list == null)
				throw new ArgumentException("must be a list", "expr");
			if (list.Count != 4 || !(list.First is Atom) || !(list.Second is Atom)
				|| !(list[2] is Atom) || !(list[3] is Atom))
				throw new ArgumentException("list must contain exactly 4 atoms");
			if (list.First.ToString() != "method-fault")
				throw new ArgumentException("first element must be 'method-fault'");
			name = ((Atom) list.Second).ToString();
			code = ((Atom) list[2]).ToUInt32(null);
			msg = ((Atom) list[3]).ToString();
		}

		public string Name
		{
			get { return name; }
		}

		public uint FaultCode
		{
			get { return code; }
		}

		public string Message
		{
			get { return msg; }
		}

		public Expression ToExpression()
		{
			List list = new List();
			list.Add(new Atom("method-fault"));
			list.Add(new Atom(name));
			list.Add(new Atom(code));
			list.Add(new Atom(msg));
			return list;
		}
	}
}